﻿using Newtonsoft.Json;
using QWManage.Utils;
using System;
using System.Collections.Generic;

namespace QWManage.API.GroupChatList92120
{
    /// <summary>
    /// 获取客户群列表 该接口用于获取配置过客户群管理的客户群列表。
    /// </summary>
    public class GroupChatListAPI
    {
        /*
        该接口用于获取配置过客户群管理的客户群列表。

        请求方式：POST（HTTPS）
        请求地址：https://qyapi.weixin.qq.com/cgi-bin/externalcontact/groupchat/list?access_token=ACCESS_TOKEN
        {
	        "status_filter": 0,
	        "owner_filter": {
		        "userid_list": ["abel"]
	        },
	        "cursor" : "r9FqSqsI8fgNbHLHE5QoCP50UIg2cFQbfma3l2QsmwI",
	        "limit" : 10
        }
         * */

        public static List<string> Invoke(string token, GroupChatListArgs args)
        {
            List<string> list = new List<string>();
            Root root = null;
            do
            {
                if (root != null && !string.IsNullOrEmpty(root.next_cursor))
                    args.cursor = root.next_cursor;

                string url = $"https://qyapi.weixin.qq.com/cgi-bin/externalcontact/groupchat/list?access_token={token}";
                string parameters = JsonConvert.SerializeObject(args);
                string result = HttpHelper.Submit(url, parameters);
                root = JsonConvert.DeserializeObject<Root>(result);

                if (root == null || root.errcode != 0) throw new Exception("API批量获取客户详情出错");

                foreach (Group_chat_list group_chat_info in root.group_chat_list)
                {
                    list.Add(group_chat_info.chat_id);
                }
            } while (root != null && !string.IsNullOrEmpty(root.next_cursor));
            return list;
        }
    }


    public class GroupChatListArgs
    {
        public int status_filter { set; get; } = 0;
        public string cursor { set; get; } = "";
        public int limit { set; get; } = 1000;
        public owner_filter owner_filter { set; get; }
    }
    public class owner_filter
    {
        public List<string> userid_list { set; get; } = new List<string>();
    }

    #region JSON
    public class Group_chat_list
    {
        /// <summary>
        /// 
        /// </summary>
        public string chat_id { get; set; }
        /// <summary>
        /// 
        /// </summary>
        public int status { get; set; }
    }

    public class Root
    {
        /// <summary>
        /// 
        /// </summary>
        public int errcode { get; set; }
        /// <summary>
        /// 
        /// </summary>
        public string errmsg { get; set; }
        /// <summary>
        /// 
        /// </summary>
        public List<Group_chat_list> group_chat_list { get; set; }
        /// <summary>
        /// 
        /// </summary>
        public string next_cursor { get; set; }
    }

    #endregion
}
